import axios from 'axios';
import cheerio from 'cheerio';

axios.defaults.baseURL = 'https://3g.163.com';

/**
 * 获取轮播图图片
 */
export async function getBannersList() {
    let banners = [];
    let url = 'https://www.163.com/';
    let resp = await axios.get(url);
    const $ = cheerio.load(resp.data);
    $('.focus_body li .cm_bigimg').each((_, el) => {
        banners.push({
            url: $('a.photo', el).attr('href'),
            title: $('a.photo', el).attr('title'),
            image: $('.photo img', el).attr('data-original') || $('.photo img', el).attr('lazy-src')
        });
    });
    return banners;
}

/**
 * 获取新闻分类
 */
export function getNewsChannels() {
    return [
        { 
            name: '首页',
            action: 'BBM54PGAwangning'
        },
        { 
            name: '国内',
            action: 'BD29LPUBwangning'
        },
        { 
            name: '国际',
            action: 'BD29MJTVwangning'
        },
        { 
            name: '历史',
            action: 'C275ML7Gwangning'
        }
    ];
}


// 由于请求新闻数据时返回的数据是JSONP，所以声明一个方法用于获取数据
const artiList = data => data;      

/**
 * 爬取新闻
 * @param {String} url 链接
 * @param {Number} page 页码
 * @param {Number} maxResult 每页数量 
 */
export async function getNewsList(action, page = 1, pageSize = 10) {
    // https://3g.163.com/touch/reconstruct/article/list/BBM54PGAwangning/20-10.html
    if (!action) {
        let channels = getNewsChannels();
        action = channels[0].action;
    }
    let startIndex = (page - 1) * pageSize;
    let url = `https://3g.163.com/touch/reconstruct/article/list/${action}/${startIndex}-${pageSize}.html`;
    let resp = await axios.get(url);
    let result = eval(resp.data);
    return { newsList: result[action], page };
}

/**
 * 获取新闻详情
 * @param {String} url 
 */
export async function getNewsDetails(docid) {
    let url = `https://3g.163.com/dy/article/${docid}.html`;
    let resp = await axios.get(url);
    const $ = cheerio.load(resp.data);
    let content = '';
    let temp = '';
    $('.content .page').find('p').each((i, el) => {
        temp = $(el).text();
        if (temp !== '' && excludeKeywords(temp)) {
            content += temp;
        }
    });
    return content;
}

/**
 * 测试是否不包含关键字，包含返回false，不包含返回true
 * @param {String} text 
 */
function excludeKeywords(text) {
    const keywords = ['原标题', '编辑', '作者', '来源', '中央纪委国家监委网站', '文/', '撰文', '关注'];
    let index = keywords.findIndex(keyword => text.includes(keyword));
    return index === -1;
}